package cn.enine.tbcharge.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import cn.enine.tbcharge.R;
import cn.enine.tbcharge.adapter.CommonAdapter;
import cn.enine.tbcharge.adapter.ViewHolder;
import cn.enine.tbcharge.base.MyBaseActivity;
import cn.enine.tbcharge.pojo.AppSfMain;
import cn.enine.tbcharge.pojo.AppSfSub;
import cn.enine.tbcharge.pojo.AppXmpy;
import cn.enine.tbcharge.pojo.RetMsg;
import cn.enine.tbcharge.util.DateConvert;
import cn.enine.tbcharge.util.HttpUrl;
import cn.enine.tbcharge.util.MyToastUtil;
import cn.enine.tbcharge.util.NetWorkUtils;
import cn.enine.tbcharge.util.SharedPreferencesUtils;
import cn.enine.tbcharge.util.StringUtils;
import cn.enine.tbcharge.util.UserClient;
import cn.enine.tbcharge.view.XListView;

public class SflistActivity extends MyBaseActivity {

    XListView listView;
    //标题
    TextView title, uname, tongbu;
    LinearLayout back,b3;
    ZLoadingDialog dialog;//加载动画
    Context con = SflistActivity.this;
    private int pageNum1 = 1;// 无关键字页数
    List<AppSfMain> list;
    private ImageView searchBtn;
    private EditText key;

    @Override
    protected void initUI() {
        setContentView(R.layout.activity_sflist);
        searchBtn = (ImageView) findViewById(R.id.cxButton);
        key = (EditText) findViewById(R.id.key);
        key.setHint("请输入病患姓名");
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        title.setText("收费记录");
        uname.setText("新增");
        back = (LinearLayout) findViewById(R.id.back);
        b3 = (LinearLayout) findViewById(R.id.b3);
        b3.setVisibility(View.VISIBLE);
        tongbu = (TextView)findViewById(R.id.tongbu) ;
        listView = (XListView) findViewById(R.id.listView);
        listView.setPullLoadEnable(true);
        dialog = new ZLoadingDialog(con);
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.parseColor("#1C86EE"))//颜色
                .setHintText("Loading...")
                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.parseColor("#1C86EE"));  // 设置字体颜色
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(NetWorkUtils.isNetworkConnected(con)){//联网状态
            getInfo();
        }else{
            getInfoNoNet();
        }
    }
    private void getInfoNoNet(){
    //            LitePal.deleteAll(AppSfMain.class);
    //            LitePal.deleteAll(AppSfSub.class);
        list = LitePal.order(" tbtime desc").find(AppSfMain.class);
        Log.i("本地list","size====="+list.size());
        listView.setPullLoadEnable(false);
        listView.setPullRefreshEnable(false);
        listView.setAdapter(new CommonAdapter(con, list, R.layout.sf_main_item) {
            @Override
            public void convert(ViewHolder helper, Object item) {
                if (item instanceof AppSfMain) {
                    AppSfMain sfMainItem = (AppSfMain) item;
                    helper.setText(R.id.xm, "姓名:"+sfMainItem.getName());
                    helper.setText(R.id.jkdah, "合计费用:"+sfMainItem.getTotalfy());
                    helper.setText(R.id.sfrq, "时间:"+DateConvert.dateToString(DateConvert.toDate(sfMainItem.getTbtime(), DateConvert.YMDHMS), DateConvert.YMDHMS)+"    ");
                }
            }
        });
    }

    @Override
    protected void initListener() {
        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getInfo();
            }
        });
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                startActivity(new Intent(con, SfaddActivity.class).putExtra("type", "add"));
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                finish();
                Bundle b = new Bundle();
                b.putSerializable("b", list.get(i- 1));
                startActivity(new Intent(con, SfaddActivity.class).putExtras(b).putExtra("type", "edit"));
            }
        });

        tongbu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                upData();
            }
        });
    }

    public void getInfo() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("page", pageNum1 + "");
        if (!StringUtils.isEmpty(key.getText().toString()))
            ps.add("name", key.getText().toString());
        UserClient.get(HttpUrl.GetSfmainList, ps, new AsyncHttpResponseHandler() {

            @Override
            public void onStart() {
                super.onStart();
            }
            @Override
            public void onFailure(int statusCode, Throwable error, String content) {
                super.onFailure(statusCode, error, content);
                //MyToastUtil.ShowToast(con, "请求失败");
                getInfoNoNet();
            }
            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                dialog.dismiss();
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    List<AppSfMain> ll = JSON.parseArray(ret.getList(), AppSfMain.class);
                    if (pageNum1 == 1)
                        list = new ArrayList<AppSfMain>();
                    for (int i = 0; i < ll.size(); i++) {
                        AppSfMain appSfMain = ll.get(i);
                        list.add(appSfMain);
                    }
                    listView.setSelection(list.size() - ll.size());
                    listView.stopRefresh();
                    listView.stopLoadMore();
                    listView.setRefreshTime("刚刚");
                    int totalPage = Integer.parseInt(ret.getTotalPage());
                    listView.setPullLoadEnable(totalPage<=1 ? false : true);
                    listView.setXListViewListener(new XListView.IXListViewListener() {
                        @Override
                        public void onRefresh() {
                            pageNum1 = 1;
                            getInfo();
                        }
                        @Override
                        public void onLoadMore() {
                            pageNum1 = pageNum1 + 1;
                            getInfo();
                        }
                    });
                    listView.setAdapter(new CommonAdapter(con, list, R.layout.sf_main_item) {
                        @Override
                        public void convert(ViewHolder helper, Object item) {
                            if (item instanceof AppSfMain) {
                                AppSfMain sfMainItem = (AppSfMain) item;
                                helper.setText(R.id.xm, "姓名:"+sfMainItem.getName());
                                helper.setText(R.id.jkdah, "合计费用:"+sfMainItem.getTotalfy()+"("+(sfMainItem.getZfstate()==1?"已支付":"未支付")+")");
                                TextView jkdah = helper.getView(R.id.jkdah);
                                if(null != sfMainItem.getZfstate() && sfMainItem.getZfstate()==1){
                                    jkdah.setTextColor(Color.GREEN);
                                }else{
                                    jkdah.setTextColor(Color.RED);
                                }
                                helper.setText(R.id.sfrq, "时间:"+DateConvert.dateToString(DateConvert.toDate(sfMainItem.getTbtime(), DateConvert.YMDHMS), DateConvert.YMDHMS)+"    ");
                            }
                        }
                    });
                } else {
                    //MyToastUtil.ShowToast(con, "获取错误");
                    getInfoNoNet();
                }
            }
        });
    }

    public void upData() {
        List<AppSfMain> appXmpyList = LitePal.findAll(AppSfMain.class);
        for (AppSfMain appSfMain : appXmpyList) {
            RequestParams ps = new RequestParams();
            ps.add("entity.NID", appSfMain.getNid());
            ps.add("entity.NAME", appSfMain.getName());
            ps.add("entity.IDNO", appSfMain.getIdno());
            ps.add("entity.PHONE", appSfMain.getPhone());
            ps.add("entity.TBTIME", appSfMain.getTbtime());
            ps.add("entity.TOTALFY", appSfMain.getTotalfy());
            ps.add("entity.ZFTYPE", appSfMain.getZftype()+"");
            ps.add("entity.ZFSTATE", appSfMain.getZfstate()+"");
            ps.add("entity.SFTOTALFY", appSfMain.getSftotalfy());
            ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
            ps.add("type", "2");
            UserClient.get(HttpUrl.UpSfmain, ps, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    super.onStart();
                }
                @Override
                public void onFailure(int statusCode, Throwable error, String content) {
                    super.onFailure(statusCode, error, content);
                }
                @Override
                public void onSuccess(String content) {
                    super.onSuccess(content);
                    dialog.dismiss();
                    RetMsg ret = JSON.parseObject(content, RetMsg.class);
                    if (ret.getCode().equals("200")) {
                        LitePal.delete(AppSfMain.class, appSfMain.getId());
                    }
                }
            });
        }

        List<AppSfSub> appSfSubList = LitePal.findAll(AppSfSub.class);
        for (AppSfSub appSfSub : appSfSubList) {
            RequestParams ps2 = new RequestParams();
            ps2.add("entity.NID", appSfSub.getNid());
            ps2.add("entity.MAINID", appSfSub.getMainid());
            ps2.add("entity.XMID", appSfSub.getXmid());
            ps2.add("entity.XMNAME", appSfSub.getXmname());
            ps2.add("entity.FY", appSfSub.getFy());
            ps2.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
            ps2.add("type", "2");
            UserClient.get(HttpUrl.UpSfsub, ps2, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    super.onStart();
                }
                @Override
                public void onFailure(int statusCode, Throwable error, String content) {
                    super.onFailure(statusCode, error, content);
                }
                @Override
                public void onSuccess(String content) {
                    super.onSuccess(content);
                    dialog.dismiss();
                    RetMsg ret = JSON.parseObject(content, RetMsg.class);
                    if (ret.getCode().equals("200")) {
                        LitePal.delete(AppSfSub.class, appSfSub.getId());
                    }
                }
            });
        }
    }
}
